package org.itboys.mobile.controller.order;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.order.KitchenOrderDto;
import org.itboys.mobile.service.mysql.mobile.order.PearlOrderService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2017/10/24.
 * @author 朱坤涛
 *  email:1124315472@qq.com
 *  DES:珍珠集_订单
 */
@Controller
@RequestMapping("/pearl/mobile/order")
public class PearlMobileOrderController extends BaseController{
    @Autowired
    private PearlOrderService orderService;
    @RequestMapping(value = "/createOrder",method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】创建订单。")
    public void createOrder(HttpServletRequest request,
                            HttpServletResponse response,
                            @ApiParam(required = true,name = "cartIds",value = "购物车ID集合(非商品ID)") @RequestParam(value = "cartIds",required = true)List<Long> cartIds,
                            @ApiParam(required = false, name = "isUsedBalance", value = "是否使用余额。[用户版]0否，1是") @RequestParam(value="isUsedBalance",required=false) Integer isUsedBalance,
                            @ApiParam(required = false, name = "addressId", value = "收货地址Id。【用户版】选择配送或【管理版】下单，需要传入") @RequestParam(value="addressId",required=false) Long addressId,
                            @ApiParam(required = false, name = "payPassword", value = "支付密码。[用户版]使余额抵扣传入") @RequestParam(value="payPassword",required=false) String payPassword,
                            @ApiParam(required = false, name = "remark", value = "订单备注。") @RequestParam(value="remark",required=false) String remark,
                            @ApiParam(value = "随机数")@RequestParam(value = "nonce",required = true)String nonce,
                            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
                            ){
            try {
                Map<String, Object> param =new HashMap<String,Object>();
                StringBuilder cartIdsStr=new StringBuilder();
                for(Long cartId:cartIds){
                    cartIdsStr.append(cartId+",");
                }
                param.put("cartIds",cartIdsStr.substring(0,cartIdsStr.length()-1).toString());//实际是字符串。cartIds=1,2,3
                param.put("isUsedBalance",isUsedBalance);
                param.put("addressId",addressId);
                param.put("payPassword",payPassword);
                param.put("remark",remark);
                param.put("nonce", nonce);
                param.put("sign", sign);

                Long memberId = AccountIdHoldUtils.getMemberId();
                Map<String,Object> result = orderService.createOrder(memberId,cartIds,isUsedBalance, addressId,
                        payPassword, remark);
                ResponseMessage.success(result);
            }catch (Exception e){
                String msg = CommonConstants.ERROMSG;
                Integer code = CommonConstants.FAIL_CODE;
                if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                    msg = e.getMessage();
                }else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                    code = CommonConstants.TOKEN_CODE;
                    msg = CommonConstants.TOKENMSG;
                }else {
                    logger.error("pearl/mobile/order/createOrder----e="+e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code,msg);
            }
    }
    @RequestMapping(value = "/select",method =RequestMethod.POST)
    @ApiOperation(value ="【用户版和管理版】分页获取订单。" )
    public void select(HttpServletRequest request,
                        HttpServletResponse response,
                       @ApiParam(required = true, name = "orderStatuses", value = "订单状态集合，支持传入多个状态。例如：orderStatuses=1,2,3" +
                               "0全部，1，待付款，2待配送，3配送中，4待评价，5已评价，6待退款， 7已退款，8待退货，9已退货,10已取消") @RequestParam(value="orderStatuses",required=true) List<Integer> orderStatuses,
                       @ApiParam(required = false, name = "createTime_start", value = "查询参数。开始时间。默认为空") @RequestParam(value = "createTime_start", required = false) String createTime_start,
                       @ApiParam(required = false, name = "createTime_end", value = "查询参数。结束时间。默认为空") @RequestParam(value = "createTime_end", required = false) String createTime_end,
                       @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                       @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                       @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                       @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                       @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
                       ){
            try {
                Long memberId = AccountIdHoldUtils.getMemberId();
                List<KitchenOrderDto> result = orderService.selectOrder(request,memberId,orderStatuses);
                ResponseMessage.success(result);
            }catch (Exception e){
                String msg = CommonConstants.ERROMSG;
                Integer code = CommonConstants.FAIL_CODE;
                if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                    msg = e.getMessage();
                }else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                    code = CommonConstants.TOKEN_CODE;
                    msg = CommonConstants.TOKENMSG;
                }else {
                    logger.error("/pearl/mobile/order/select----e="+e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code,msg);
            }
    }
    @RequestMapping(value = "/findOne",method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】查看订单详情。")
    public void findOne(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(required = true, name = "orderId", value = "订单Id") @RequestParam(value = "orderId", required = true)Long orderId,
                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
                        ){
            try {
                Long memberId = AccountIdHoldUtils.getMemberId();
                KitchenOrderDto result = orderService.findOne(orderId,memberId);
                ResponseMessage.success(result);
            }catch (Exception e){
                String msg =CommonConstants.ERROMSG;
                Integer code=CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                    msg=e.getMessage();
                    //token已过期
                }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                    code=CommonConstants.TOKEN_CODE;
                    msg=CommonConstants.TOKENMSG;
                }else{
                    logger.error("/pearl/mobile/order/findOne----e="+e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code,msg);
            }
    }
    @RequestMapping(value = "/cancel",method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】取消订单。1用户商城订单，【待付款】才能取消，3管理版待配送才能取消。")
    public void cacel(HttpServletRequest request,
                      HttpServletResponse response,
                      @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                      @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                      @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
                      ){
            try {
                Map<String, Object> param =new HashMap<String,Object>();
                param.put("orderId",orderId);
                param.put("nonce", nonce);
                param.put("sign", sign);
                boolean signSer = MobileSignUtils.signCheck(param, sign);
                Long memberId = AccountIdHoldUtils.getMemberId();
                orderService.cancelOrder(orderId,memberId);
                ResponseMessage.success();
            }catch (Exception e){
                String msg =CommonConstants.ERROMSG;
                Integer code=CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                    msg=e.getMessage();
                    //token已过期
                }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                    code=CommonConstants.TOKEN_CODE;
                    msg=CommonConstants.TOKENMSG;
                }else{
                    logger.error("/pearl/mobile/order/cancel----e="+e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code,msg);
            }
    }
    @RequestMapping(value = "/sendOrder",method = RequestMethod.POST)
    @ApiOperation(value = "【管理版】配送订单。orderStatus==2才能配送。")
    public void sendOrder(HttpServletRequest request,
                          HttpServletResponse response,
                          @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                          @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                          @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
                          ){
            try {
                Map<String, Object> param =new HashMap<String,Object>();
                param.put("orderId",orderId);
                param.put("nonce", nonce);
                param.put("sign", sign);
                boolean signSer = MobileSignUtils.signCheck(param, sign);
                Long memberId = AccountIdHoldUtils.getMemberId();
                orderService.sendOrder(orderId,memberId);
                ResponseMessage.success();
            }catch (Exception e){
                String msg =CommonConstants.ERROMSG;
                Integer code=CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                    msg=e.getMessage();
                    //token已过期
                }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                    code=CommonConstants.TOKEN_CODE;
                    msg=CommonConstants.TOKENMSG;
                }else{
                    logger.error("/pearl/mobile/order/sendOrder----e="+e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code,msg);
            }
    }
    @RequestMapping(value = "/confirmReceive",method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】确认收货。配送中订单才能确认收货，不区分订单类型。")
    public void confirmReceive(HttpServletRequest request,
                               HttpServletResponse response,
                               @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                               @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                               @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ){
        try{
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);

            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.confirmReceive(orderId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;

            }else{
                logger.error("/pearl/mobile/order/confirmReceive----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value = "/comment",method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】评论订单，每个商品最大传入三张图片，没有图片的评论，用noImage字符串，固定images集合占位。")
    public void comment(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true)Long orderId,
                        @ApiParam(required = true, name = "productIds", value = "商品ID集合(productIds,contents,scores大小，顺序对应)。例如：productIds=1,2,3") @RequestParam(value = "productIds", required = true) List<Long> productIds,
                        @ApiParam(required = true, name = "contents", value = "评论内容集合，默认值：系统默认好评。(productIds,contents,scores大小，顺序对应)。例如：contents=1,2,3") @RequestParam(value = "contents", required = true) List<String> contents,
                        @ApiParam(required = true, name = "scores", value = "评分(0-5)集合。默认值：5。（productIds,contents,scores大小，顺序对应）。例如：scores=1,2,3") @RequestParam(value = "scores", required = true)List<Integer> scores,
                        @ApiParam(required = true, name = "images", value = "图片集合；，固定大小=productIds集合大小*3。每个商品限制最大传入三张，没有图片的使用noImage字符传固定值，在集合中占位") @RequestParam(value = "images", required = true)List<String> images,
                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign

    ){
            try{
                Long memberId = AccountIdHoldUtils.getMemberId();
                orderService.commentOrder(orderId,productIds, contents,scores,images,memberId);
                ResponseMessage.success();
            }catch (Exception e){
                String msg =CommonConstants.ERROMSG;
                Integer code=CommonConstants.FAIL_CODE;
                //自定义异常（签名错误）
                if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                    msg=e.getMessage();
                    //token已过期
                }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                    code=CommonConstants.TOKEN_CODE;
                    msg=CommonConstants.TOKENMSG;
                }else{
                    logger.error("/pearl/mobile/order/comment----e="+e.getMessage());
                }
                e.printStackTrace();
                ResponseMessage.error(code,msg);
            }
    }
    @RequestMapping(value = "/getOrderNumber",method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】获取给订单状态数量。")
    public void getOrderNumber(HttpServletRequest request,
                               HttpServletResponse response,
                               @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                               @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
                               ){
         try {
             Long memberId = AccountIdHoldUtils.getMemberId();
             Map<String,Object> result=orderService.getOrderNumber(memberId);
             ResponseMessage.success(result);
         }catch (Exception e){
             String msg = CommonConstants.ERROMSG;
             Integer code=CommonConstants.FAIL_CODE;
             //自定义异常（签名错误）
             if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                 msg=e.getMessage();
                 //token已过期
             }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                 code=CommonConstants.TOKEN_CODE;
                 msg=CommonConstants.TOKENMSG;
             }else{
                 logger.error("/pearl/mobile/order/getOrderNumber----e="+e.getMessage());
             }
             e.printStackTrace();
             ResponseMessage.error(code,msg);
         }
    }
}
